package com.qitianyong.selfclass;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.util.Log;

import com.gkusbsdk.SZUSBCommand;
import com.gkusbsdk.SZUSBSDK;
import com.gkusbsdk.SZUSBTime;
import com.gkusbsdk.USB;
import com.sgkusbcamdemo.CustomApp;
import com.sgkusbcamdemo.R;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import de.greenrobot.event.EventBus;


/**
 * Created by gy on 2017/5/18.
 */

public class FindDeviceUtils {
    private static boolean canUseDevVideo;

    public static long lastConnectTime = 0;
    static ExecutorService findDeviceThread = Executors.newSingleThreadExecutor();

    public static void findDevice() {

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);//插
//intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);//拔
        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);  //完全拔出
        intentFilter.addDataScheme("file");//没有这行监听不起作用
        CustomApp.customApp.registerReceiver(receiver, intentFilter);

    }

    private static final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.e("TAG", "INIT === " + intent.getAction());
            if (intent.getAction().equals("android.intent.action.MEDIA_MOUNTED")) {//U盘插入
                String path = intent.getDataString();
                String pathString = path.split("file://")[1];//U盘路径
                Log.e("TAG", "U盘插入" + pathString);
                usb_path = pathString + "/";//加一个反斜杠
                Log.e("getExternalPath--", usb_path);
                findDeviceThread.execute(findDeviceRunnable);
            } else if (intent.getAction().equals("android.intent.action.MEDIA_REMOVED")) {//U盘拔出
                Log.e("TAG", "U盘拔出");
            } else {
                Log.e("TAG", "未检测到");
            }
        }
    };
    private static boolean beginSearchDevices = false;

    private static String usb_path = "";
//    private static Runnable findDeviceRunnable = new Runnable() {
//        @Override
//        public void run() {
//            LogUtils.i("System","findDeviceRunnable");
//                if (!beginSearchDevices && GKDevice.__hDevice == 0) {
//                    beginSearchDevices = true;
//                    ArrayList<UsbDevice> matchingHostDevicess = null;
//                    try {
//                        matchingHostDevicess = UsbDeviceFilter.getMatchingHostDevices(CustomApp.customApp, R.xml.device_filter);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                    if (matchingHostDevicess == null || matchingHostDevicess.size() == 0) {
//                        beginSearchDevices = false;
//                        LogUtils.i("System","findDeviceRunnable end");
//                        return;
//                    }
//                    if(false){
//                        //多次初始化，防止设备刚开机时响应不及时
//                        for (int j = 0; j < 10 ; j++) {
//                            USB[] usb = new USB[32];
//                            int count = SZUSBSDK.GKUSB_SearchVideoNodeCams(usb);
//                            for (int i = 0; i < count && beginSearchDevices; i++) {
//                                long hDevice = SZUSBSDK.GKUSB_CreateVideoNodeCam(usb[i]);
//                                boolean suc = initDevice(hDevice);
//                                if(suc){
//                                    beginSearchDevices = false;
//                                    LogUtils.i("System","findDeviceRunnable end");
//                                    return;
//                                }
//                                PublicMethod.sleep(100);
//                            }
//                        }
//                    }else{
//                        UsbManager usbManager = (UsbManager) CustomApp.customApp.getSystemService(Context.USB_SERVICE);
//                        ArrayList<UsbDevice> matchingHostDevices = null;
//                        try {
//                            matchingHostDevices = UsbDeviceFilter.getMatchingHostDevices(CustomApp.customApp, R.xml.device_filter);
//                            for (final UsbDevice usbDevice : matchingHostDevices) {
//                                if (usbManager.hasPermission(usbDevice)) {
//                                    initUsb(usbDevice);
//                                    break;
//                                }
//                            }
//                        } catch (Exception ignored) {
//                        }
//                    }
//                }
//            LogUtils.i("System","findDeviceRunnable end");
//            beginSearchDevices = false;
//        }
//    };


    private static Runnable findDeviceRunnable = new Runnable() {
        @Override
        public void run() {
//            if (System.currentTimeMillis() > 1701273600000L) {
//                return;
//            }
            beginSearchDevices = true;
            while (true) {
                if (beginSearchDevices && (GKDevice.__hDevice == 0)) {
  /*                  ArrayList<UsbDevice> matchingHostDevicess = null;
                    try {
                        matchingHostDevicess = UsbDeviceFilter.getMatchingHostDevices(CustomApp.customApp, R.xml.device_filter);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (matchingHostDevicess == null || matchingHostDevicess.size() == 0) {
                        beginSearchDevices = false;
                        ZyLog.d("isGKUSBDevice:" + false);
                        LogUtils.addLog("isGKUSBDevice:" + false);
                        continue;
                    }
                    LogUtils.addLog("beginSearchDevices =" + beginSearchDevices);
                    */

                    SharedPreferences config = CustomApp.customApp.getSharedPreferences("config", 0);
                    boolean canUseDevVideo = config.getBoolean("canUseDevVideo", false);

                    //for (int j = 0; j < time && beginSearchDevices; j++) {
                    while (beginSearchDevices) {

                        //upgradeRootPermission(i);
                        //upgradeRootPermissionVs1(1);
                        //upgradeRootPermissionVs2(2);
                        //long hDevice = GKUSBSDK.GKUSB_CreateVideoNodeCam(usb[i]);  //20230920.deyue mark
                        long hDevice = SZUSBSDK.GKUSB_CreateVideoVsUvcCam(usb_path);
                        Log.d("xx", "GKUSB_CreateVideoNodeCam =" + hDevice);
                        if (hDevice != 0) {
                            PublicMethod.sleep(500);
                            SZUSBTime usbTime = PublicMethod.CurrentTime2USBTime();
                            Log.i("GKDevice", "time:" + usbTime.__year + "-" + usbTime.__month + "-" + usbTime.__day +
                                    " " + usbTime.__hour + ":" + usbTime.__minute + ":" + usbTime.__second);
                            int ret = SZUSBSDK.GKUSB_SetParam(hDevice, SZUSBCommand.CMD_SYNC_TIME, usbTime);
                            Log.i("GKDevice", "Sync time result" + ret);
                            if (ret == 0) {
                                PublicMethod.sleep(500);
                                ret = SZUSBSDK.GKUSB_SetProtocol(hDevice, SZUSBCommand.PROTOCOL_TYPE.TYPE_NEW);
                                //ret = 1;
                                if (ret == 1) {  // 设置成功
                                    GKDevice.__hDevice = hDevice;
                                    if (!FindDeviceUtils.canUseDevVideo) {
                                        FindDeviceUtils.canUseDevVideo = true;
                                        config.edit().putBoolean("canUseDevVideo", true).apply();
                                    }
                                    EventBus.getDefault().post(new BaseActivityEvent(BaseActivityEvent.OPENSTREAM));
                                    beginSearchDevices = false;
                                } else {
                                    SZUSBSDK.GKUSB_Destroy(hDevice);
                                }
                                Log.i("GKDevice", "-----SetProtocol ------ " + ret);
                            } else {
                                SZUSBSDK.GKUSB_Destroy(hDevice);
                            }
                            PublicMethod.sleep(300);
                        }
                        PublicMethod.sleep(200);

                        PublicMethod.sleep(3000);
                    }
/*

                    if (beginSearchDevices && !FindDeviceThread.canUseDevVideo) {
                        UsbManager usbManager = (UsbManager) CustomApp.customApp.getSystemService(Context.USB_SERVICE);
                        PendingIntent mPermissionIntent = PendingIntent.getBroadcast(CustomApp.customApp, 0, new Intent(ACTION_USB_PERMISSION), 0);
                        ArrayList<UsbDevice> matchingHostDevices = new ArrayList<>();
                        try {
                            matchingHostDevices = UsbDeviceFilter.getMatchingHostDevices(CustomApp.customApp, R.xml.device_filter);
                        } catch (Exception e) {
                        }
                        ZyLog.d("beginUsbDevices matchingHostDevices");
                        for (final UsbDevice usbDevice : matchingHostDevices) {
                            LogUtils.addLog("beginUsbDevices");
                            if (usbManager.hasPermission(usbDevice)) {
                                ZyLog.d("beginUsbDevices initDevUsbDevice");
                                USBPermissionRequestResultReceiver.initDevUsbDevice(usbDevice);
                            } else {
                                ZyLog.d("beginUsbDevices requestPermission");
                                usbManager.requestPermission(usbDevice, mPermissionIntent);
                            }
                            break;
                        }
                    }
*/

                } else if (beginSearchDevices) {
                    lastConnectTime = System.currentTimeMillis();
                }
                beginSearchDevices = false;
                PublicMethod.sleep(2000);
            }
        }
    };

    public static void initUsb(UsbDevice usbDevice) {
        UsbManager usbManager = (UsbManager) CustomApp.customApp.getSystemService(Context.USB_SERVICE);
        UsbDeviceConnection connection = usbManager.openDevice(usbDevice);
        if (connection == null) {
            return;
        }
        final String[] v = usbDevice.getDeviceName().split("/");
        String usbfs = null;
        if ((v.length > 2)) {
            final StringBuilder sb = new StringBuilder(v[0]);
            for (int i = 1; i < v.length - 2; i++)
                sb.append("/").append(v[i]);
            usbfs = sb.toString();
        }
        int time = 10;
        while (time-- > 0) {
            long hDevice = SZUSBSDK.GKUSB_CreateBusNodeCam(connection.getFileDescriptor(), usbDevice.getVendorId(), usbDevice.getProductId(), Integer.parseInt(v[v.length - 2]), Integer.parseInt(v[v.length - 1]), usbfs);
            boolean suc = initDevice(hDevice);
            if (suc) {
                GKDevice.usbConnection = connection;
                break;
            }
        }
        if (GKDevice.__hDevice == 0) {
            connection.close();
        }
    }

    public static boolean initDevice(long hDevice) {
        if (hDevice != 0) {
            PublicMethod.sleep(500);
            SZUSBTime usbTime = PublicMethod.CurrentTime2USBTime();
            int ret = SZUSBSDK.GKUSB_SetParam(hDevice, SZUSBCommand.CMD_SYNC_TIME, usbTime);
            if (ret == 0) {
                PublicMethod.sleep(500);
                ret = SZUSBSDK.GKUSB_SetProtocol(hDevice, SZUSBCommand.PROTOCOL_TYPE.TYPE_NEW);
                if (ret == 1) {  // 设置成功
                    GKDevice.__hDevice = hDevice;
                    EventBus.getDefault().post(new BaseActivityEvent(BaseActivityEvent.OPENSTREAM));
                    return true;
                } else {
                    SZUSBSDK.GKUSB_Destroy(hDevice);
                }
                LogUtils.i("GKDevice", "-----SetProtocol ------ " + ret);
            } else {
                SZUSBSDK.GKUSB_Destroy(hDevice);
            }
            PublicMethod.sleep(300);
        }

        return false;
    }
}
